package com.edu.neusoft.users.controller;

import com.edu.neusoft.users.domain.User;
import com.edu.neusoft.users.service.IUserService;
import com.edu.neusoft.users.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/users")
@Api(value = "UserController", tags = {"用户管理接口"})
public class UserController {

    @Autowired
    private IUserService userService;

    // 获取所有用户
    @GetMapping("/list")
    @ApiOperation(value = "获取所有用户", notes = "返回所有用户的列表信息")
    public AjaxResult list(){
        List<User> userList = userService.selectUserList();
        return AjaxResult.success(userList);
    }

    // 根据name获取用户
    @GetMapping("/{Username}")
    @ApiOperation(value = "根据name获取用户" , notes = "返回所获取的用户信息")
    public AjaxResult getUserByName(@PathVariable("Username") String Username) {
        User user = userService.getUserByName(Username);
        return user !=null ? AjaxResult.success(user) : AjaxResult.error("用户不存在");
    }

    // 创建用户
    @PostMapping("/createUser")
    @ApiOperation(value = "创建用户" , notes = "根据提供用户的信息创建用户")
    public AjaxResult createUser(@RequestBody User user) {
        int result = userService.insertUser(user);

        if (result>0)
        {
            return AjaxResult.success("创建用户成功");
        }
        else {
            return AjaxResult.error("创建用户失败");
        }
    }

    // 更新用户
    @PutMapping("/updateUser")
    @ApiOperation(value = "更新用户信息", notes = "根据提供的信息更新用户")
    public AjaxResult updateUser( @RequestBody User user) {
        int result = userService.updateUser(user);

        if (result>0)
        {
            return AjaxResult.success("更新用户成功");
        }
        else {
            return AjaxResult.error("更新用户失败");
        }
    }

    // 删除用户
    @DeleteMapping("/{Username}")
    @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
    public AjaxResult deleteUser(@PathVariable String Username) {
       String result = userService.deleteUser(Username);
        return result !=null ? AjaxResult.success(result) : AjaxResult.error("用户不存在");
    }
}